import mqtt from '../../utils/mqtt.min.js';
const Logger = require('../../utils/logger');

//连接的服务器域名，注意格式！！！
const host = 'wxs://mqtt.androidex.cn/mqtt';
Page({
  data: {
    client: null,
    //记录重连的次数
    reconnectCounts: 0,
    //MQTT连接的配置
    options: {
      protocolVersion: 5, //MQTT连接协议版本
      clientId: 'wx_12345678' ,
      keepalive: 120,          // 关键参数：建议2-5分钟
      clean: true,
      password: 'smartiot',
      username: 'smartiot',
      reconnectPeriod: 10000, //1000毫秒，两次重新连接之间的间隔
      connectTimeout: 30 * 1000, //1000毫秒，两次重新连接之间的间隔
      resubscribe: true, //如果连接断开并重新连接，则会再次自动订阅已订阅的主题（默认true）
      will: {
        topic: 'client/status',
        payload: 'connection_lost',
        qos: 1,
        retain: false
      },
      headers: {
        'Upgrade': 'websocket',
        'Connection': 'Upgrade',
        'Content-Type': 'application/json',
        'X-Requested-With': 'XMLHttpRequest',  // 微信小程序特殊标识
        'Sec-WebSocket-Extensions': 'permessage-deflate; client_max_window_bits',
        'Sec-WebSocket-Protocol': 'mqtt', // 显式添加协议头
        'Sec-WebSocket-Version': '13'
      }
    }
  },
  onClick_connect: function() {

    var that = this;

    this.logger.log("Start connecting...");
    //开始连接
    this.data.client = mqtt.connect(host, this.data.options);
    this.data.client.on('connect', function(connack) {
      that.logger.log("连接成功");
      // wx.showToast({
      //   title: '连接成功'
      // })
      this.data.client.subscribe('/kc031srv/DOOR031-4F351E1696994223A526/pub', function(err, granted) {
          if (!err) {
            that.logger.log("订阅成功");
          } else {
            that.logger.log("订阅失败");
          }
        })
    })

    //服务器下发消息的回调
    that.data.client.on("message", function(topic, payload) {
      that.logger.log(" 收到 topic:" + topic + " , payload :" + payload)
      // wx.showModal({
      //   content: " 收到topic:[" + topic + "], payload :[" + payload + "]",
      //   showCancel: false,
      // });
    })


    //服务器连接异常的回调
    that.data.client.on("error", function(error) {
      that.logger.log(" 服务器 error 的回调" + error)

    })

    //服务器重连连接异常的回调
    that.data.client.on("reconnect", function() {
      that.logger.log(" 服务器 reconnect的回调");
    })


    //服务器连接异常的回调
    that.data.client.on("offline", function(errr) {
      that.logger.log(" 服务器offline的回调");
    })


  },
onClick_officeroom: function() {
  var that = this;
  if (this.data.client && this.data.client.connected) {
    this.data.client.publish('/kc031srv/DOOR031-4F351E1696994223A526/sub', 'FB010C50010202016F6E696E7075');
    that.logger.log('发送开门命令成功');
    wx.showToast({
      title: '发送开门命令成功'
    })
  } else {
    that.logger.log('请先连接服务器');
    wx.showToast({
      title: '请先连接服务器',
      icon: 'none',
      duration: 2000
    })
  }
},
onClick_tearoom: function() {
  var that = this;
  if (this.data.client && this.data.client.connected) {
    this.data.client.publish('/kc031srv/DOOR031-4F351E1696994223A526/sub', 'FB010C50010201016F6E696E7075740000FE');
    that.logger.log('发送开门命令成功');
    wx.showToast({
      title: '发送开门命令成功'
    });
  } else {
    that.logger.log("请先连接服务器");
    wx.showToast({
      title: '请先连接服务器',
      icon: 'none',
      duration: 2000
    })
  }
},
onClick_SubOne: function() {
    if (this.data.client && this.data.client.connected) {
      //仅订阅单个主题
      this.data.client.subscribe('/kc031srv/#', function(err, granted) {
        if (!err) {
          wx.showToast({
            title: '订阅主题成功'
          })
        } else {
          wx.showToast({
            title: '订阅主题失败',
            icon: 'fail',
            duration: 2000
          })
        }
      })
    } else {
      wx.showToast({
        title: '请先连接服务器',
        icon: 'none',
        duration: 2000
      })
    }
  },
  onClick_SubMany: function() {

    if (this.data.client && this.data.client.connected) {
      //仅订阅多个主题
      this.data.client.subscribe({
        '/kc031srv/kc031srv/#': {
          qos: 1
        },
        '/kc031srv/heating/#': {
          qos: 1
        }
      }, function(err, granted) {
        if (!err) {
          wx.showToast({
            title: '订阅多主题成功'
          })
        } else {
          wx.showToast({
            title: '订阅多主题失败',
            icon: 'fail',
            duration: 2000
          })
        }
      })
    } else {
      wx.showToast({
        title: '请先连接服务器',
        icon: 'none',
        duration: 2000
      })
    }
  },
  onClick_PubMsg: function() {
    if (this.data.client && this.data.client.connected) {
      this.data.client.publish('hello', 'i am  from wechat msg');
      wx.showToast({
        title: '发布成功'
      })
    } else {
      wx.showToast({
        title: '请先连接服务器',
        icon: 'none',
        duration: 2000
      })
    }
  },
  onClick_unSubOne: function() {
    if (this.data.client && this.data.client.connected) {
      this.data.client.unsubscribe('/kc031srv/#');
    } else {
      wx.showToast({
        title: '请先连接服务器',
        icon: 'none',
        duration: 2000
      })
    }
  },
  onClick_unSubMany: function() {
    if (this.data.client && this.data.client.connected) {
      this.data.client.unsubscribe(['/kc031srv/kc031srv/#', '/kc031srv/heating/#']);
    } else {
      wx.showToast({
        title: '请先连接服务器',
        icon: 'none',
        duration: 2000
      })
    }
  },
  onLoad: function() {
    // // 网络状态监听（真机必需）
    // wx.onNetworkStatusChange(res => {
    //   if (!res.isConnected) client.end();
    //   else if (!client.connected) client.reconnect();
    // });
    this.logger = new Logger(this)
    this.logger.log('页面加载完成')   
    this.onClick_connect()
    wx.setNavigationBarTitle({
      title: '门禁控制'
    })
  },
  onShow() {
    // this.logger.log('页面显示')
  }
})